package com.wondertek.mam.tag.wordSource.impl;

import com.wondertek.mam.tag.tagrep.TagRep;
import com.wondertek.mam.tag.wordSource.bean.NetHotWord;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 百度词源
 * Created by wangdongxu on 2017-09-11 下午 15:51:35.
 */
public class BaiduHotTodayWordSource extends WordSourceAbstract {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaiduHotTodayWordSource.class);

    private String urlPrefix = "http://top.baidu.com/buzz?b="; //url 前缀
    private List<String> urlIds; //url中的d参数
    private Integer hotThreshold; //热词阀值

    public BaiduHotTodayWordSource(TagRep tagRep, List<String> urlIds, Integer hotThreshold) {
        super(tagRep);
        this.urlIds = urlIds;
        this.hotThreshold = hotThreshold;
    }

    public NetHotWord getHotWordsByUrl(String url) {
        LOGGER.info("获取百度热点:" + url);
        try {
            Document doc = Jsoup.connect(url).get();
            Elements topTitleEle = doc.getElementsByClass("top-title");
            String keyWord = topTitleEle.get(0)
                .getElementsByTag("h2")
                .html()
                .replaceAll("排行榜", "")
                .replaceAll("今日", "");
            if (doc.getElementsByTag("tbody").size()==0){
                LOGGER.debug("百度该url结果为空:"+url);
                return null;
            }
            Map<String, Boolean> collect = doc.getElementsByTag("tbody").get(0).getElementsByTag("tr")
                .parallelStream()
                .filter(element -> element.getElementsByClass("list-title").size() != 0)
                .map(ele -> {
                    String word = ele.getElementsByClass("list-title")
                        .attr("href")
                        .split("(&w=)|(&wd=)")[1];
                    word = URLDeCodeGBK(word);
                    Integer score;
                    try {
                        score = Integer.parseInt(ele.getElementsByClass("last").get(0).getElementsByTag("span").html());
                    } catch (NumberFormatException e) {
                        score = 0;
                    }
                    if (score >= hotThreshold) {
                        return "1" + word;
                    }
                    return "0" + word;
                })
                .collect(Collectors.toMap(key -> key.substring(1), value -> value.substring(0, 1).equals("1")));
            LOGGER.debug("百度结果"+url+"--->"+collect);
            return new NetHotWord(keyWord, collect);
        } catch (Exception e) {
            LOGGER.error("获取百度热点出现错误:" + url);
        }
        return null;
    }

    @Override
    public List<String> getUrls(){
        return urlIds
            .parallelStream()
            .map(s -> urlPrefix + s)
            .collect(Collectors.toList());
    }

    public static String URLDeCodeGBK(String url) {
        try {
            List<String> hexStrs = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e" ,"f", "A", "B", "C", "D", "E","F");
            String newStr = "";
            String[] split = url.split("%");
            int sum = Arrays.asList(split).parallelStream().mapToInt(String::length).sum();
            int endB = url.length() - sum - split.length+1;

            for (int i = 0; i < split.length; i++) {
                String str = split[i];
                if (i == 0) {
                    newStr += str;
                    continue;
                }
                if (str.isEmpty()) {
                    newStr += URLEncoder.encode("%", "GBK");
                } else if (str.length() == 1) {
                    newStr += URLEncoder.encode("%" + str, "GBK");
                } else {
                    if (hexStrs.contains(str.substring(0, 1))&&hexStrs.contains(str.substring(1, 2))){
                        newStr = newStr + "%" + str.substring(0,2);
                    }else {
                        newStr = newStr + URLEncoder.encode("%" + str.substring(0,2),"GBK");
                    }
                    if (str.length()>2)
                        if (URLEncoder.encode(str.substring(2,3),"GBK").equals(str.substring(2,3))){
                            newStr = newStr + "%" +Integer.toHexString((int)str.charAt(2)) + str.substring(3);
                        }else {
                            newStr = newStr + str.substring(2);
                        }
                }

            }
            String result = URLDecoder.decode(newStr, "GBK");
            for (int i = 0; i < endB; i++) {
                result += "%";
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
